package com.browan.demo;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.browan.demo.http.MeetingApi;
import com.browan.demo.http.MeetingReturned;
import com.browan.freeppmobile.jni.FreeppKit;
import com.browan.freeppmobile.jni.RingUtil;

public class MeetingActivity extends Activity{

	private ListView mMemberList = null;
	private Button mQuitButton = null;
	private UiHandler mHandler = null;
	
	private MemberAdapter mAdapter = null;
	
	private Timer mTimer = null;
	private RefreshTask mRefreshTask = new RefreshTask();
	private CommandReceiver mReceiver = null;
	private int mMemberCount = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.meeting);
		mHandler = new UiHandler();
		
		
		mMemberList = (ListView) findViewById(R.id.member_list);
		mQuitButton = (Button) findViewById(R.id.quit_btn);
		
		mQuitButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				FreeppKit.getInstance().hangup();
				FreeppKit.inMeeting = false;
				RingUtil.stopRingback();
				FreeppKit.needRingback = false;
				MeetingActivity.this.finish();
			}
			
		});
		
		mAdapter = new MemberAdapter(this);
		
		mMemberList.setAdapter(mAdapter);
		mMemberList.setItemsCanFocus(false);
		mMemberList.setChoiceMode(ListView.CHOICE_MODE_NONE);
		
		if(FreeppKit.needRingback) {
			RingUtil.startRingback(this);
		}
		
		mReceiver = new CommandReceiver();
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		IntentFilter filter = new IntentFilter();
		filter.addAction("UI.HANGUP");
		this.registerReceiver(mReceiver, filter);
		
		if(!FreeppKit.inMeeting) 
			finish();
		else  {
			mTimer = new Timer();
			mTimer.schedule(mRefreshTask, 1000, 10*1000);
		}
			
	}

	@Override
	protected void onStop() {
		super.onStop();
		mTimer.cancel();
		this.unregisterReceiver(mReceiver);
	}

	
	private class UiHandler extends Handler {

		@Override
		public void handleMessage(Message msg) {
			switch(msg.what) {
			case 1: //refresh list
				mAdapter.notifyDataSetChanged();
				break;
			case 2: //hangup
				AlertDialog.Builder builder = new AlertDialog.Builder(MeetingActivity.this);
				builder.setMessage("会议通话中止，点击确定退出。");
				builder.setCancelable(false);
				builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						MeetingActivity.this.finish();
					}
				});
				builder.show();
				break;
			case 3: //play new coming sound
				MediaPlayer player = MediaPlayer.create(MeetingActivity.this, R.raw.newcoming);
				player.start();
				break;
			case 4: //stop ringback
				RingUtil.stopRingback();
				FreeppKit.needRingback = false;
				break;
				
			}
			super.handleMessage(msg);
		}
	}

	private int getMemberCount(String[] array) {
		HashSet<String> set = new HashSet<String>();
		for(String str : array) {
			set.add(str);
		}
		set.remove("NULL");
		set.remove(FreeppKit.e164Number);
		return set.size();
	}
	
	private class RefreshTask extends TimerTask {

		@Override
		public void run() {
			Log.i("MeetingActivity", "Refresh");
			MeetingReturned returned = MeetingApi.getInstance().getMeetingStatus(FreeppKit.e164Number);
			if(returned != null && returned.members != null) {
				int n = getMemberCount(returned.members);
				if(FreeppKit.needRingback && n > 0) {
					mHandler.sendEmptyMessage(4);
				}
				
				if(n > mMemberCount) {
					mHandler.sendEmptyMessage(3);
					mMemberCount = n;
				}
								
				Set<String> set = FreeppKit.getInstance().meetingMembers.keySet();
				for(String k: set)
				{
					FreeppKit.getInstance().meetingMembers.put(k, false);
				}
				
				for(String m: returned.members) {
					Log.i("Meeting Member:", m);
					if(m.equals("NULL")) break;
					FreeppKit.getInstance().meetingMembers.put(m, true);
				}
				mHandler.sendEmptyMessage(1);
			}
		}
		
	}
	
	private class MemberAdapter extends BaseAdapter
	{
		private ArrayList<String> mlist = new ArrayList<String>();
		private LayoutInflater minflater = null;
		
		public MemberAdapter(Context c)
		{
			minflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}
		
		@Override
		public void notifyDataSetChanged() {
			mlist.clear();
			mlist.addAll(FreeppKit.getInstance().meetingMembers.keySet());
			super.notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			return mlist.size();
		}

		@Override
		public Object getItem(int position) {
			return mlist.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View item = minflater.inflate(R.layout.member, null);
			TextView txtView = (TextView) item.findViewById(R.id.name);
			String number = mlist.get(position);
			txtView.setText(number);
			if(FreeppKit.getInstance().meetingMembers.get(number)) {
				txtView.setTextColor(0xffffffff);
			}
			else {
				txtView.setTextColor(0xff555555);
			}
			
			return item;
		}
	}
	
	private class CommandReceiver extends BroadcastReceiver
	{

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if(action.equals("UI.HANGUP")) {
				mHandler.sendEmptyMessage(2);
			}
			
		}
		
	}
}
